package com.example.testproject.adapter

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.example.testproject.R
import com.example.testproject.activity.SelectParentBean
import kotlinx.android.synthetic.main.select_parent.view.*

/**
 *
 * @ClassName: SelectAdapter
 * @Author: android 超级兵
 * @CreateDate: 10/19/21$ 3:13 PM$
 * TODO
 */
class SelectAdapter(data: List<MultiItemEntity>) :
    BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder>(data) {
    companion object {
        const val SELECT_PARENT = 0
        const val SELECT_CHILD = 1
    }

    init {
        addItemType(SELECT_PARENT, R.layout.select_parent)
        // addItemType(SELECT_CHILD, R.layout.recylcer_view)
    }

    val recyclerList = ArrayList<RecyclerView>(data.size)

    override fun convert(helper: BaseViewHolder, item: MultiItemEntity) {
        when (helper.itemViewType) {
            SELECT_PARENT -> {
                if (item is SelectParentBean) {
                    helper.setText(R.id.tvParent, item.title)
                    helper.itemView.tvParent.setOnClickListener {
                        item.isVisibility = !item.isVisibility

                        click?.onParentClick(helper.adapterPosition, item)
                    }

                    val rootRecyclerView = helper.itemView.recyclerView
                    recyclerList.add(rootRecyclerView)


                    childRecyclerView(rootRecyclerView, item.child, item.isSingleChoice)
                }
            }
        }
    }

    private fun childRecyclerView(
        rootRecyclerView: RecyclerView,
        item: List<SelectParentBean.SelectChildBean>,
        isSingleChoice: Boolean,
    ) {
        var tempSize = item.size
        if (tempSize >= 4) {
            tempSize = 4
        }
        rootRecyclerView.layoutManager = GridLayoutManager(mContext, tempSize)
        val selectChildAdapter = SelectChildAdapter(item, isSingleChoice)
        rootRecyclerView.adapter = selectChildAdapter


        selectChildAdapter.click = object : SelectChildAdapter.SelectChildListener {

            override fun onSingleChoiceClick(adapterPosition: Int) {
                selectChildAdapter.data.forEach {
                    it.isChildSelect = false
                }
                selectChildAdapter.notifyDataSetChanged()
            }
        }
    }

    interface OnSelectAdapterClickListener {
        fun onParentClick(position: Int, item: SelectParentBean)
    }

    var click: OnSelectAdapterClickListener? = null
}